package com.util;

import com.common.constants.Constants;
import com.common.model.ListNode;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 通用工具类
 *
 * @author think
 * @version 1.0.0
 */
public class CommonUtil {

    /**
     * 数据显示
     *
     * @param array 数组
     */
    public static <T extends Number> void display(T[] array) {
        if (array.length > 0) {
            Arrays.stream(array)
                    .forEach(
                            p -> {
                                System.out.print(p);
                                System.out.print(" ");
                            });
            System.out.println();
        }
    }

    /**
     * 交换对应位置的数组元素
     *
     * @param array    数组
     * @param indexOne 序号
     * @param indexTwo 序号
     */
    public static void swap(Integer[] array, int indexOne, int indexTwo) {
        if (indexOne != indexTwo) {
            array[indexTwo] = array[indexOne] ^ array[indexTwo];
            array[indexOne] = array[indexOne] ^ array[indexTwo];
            array[indexTwo] = array[indexOne] ^ array[indexTwo];
        }
    }

    public static void swap(int[] array, int indexOne, int indexTwo) {
        if (indexOne != indexTwo) {
            array[indexTwo] = array[indexOne] ^ array[indexTwo];
            array[indexOne] = array[indexOne] ^ array[indexTwo];
            array[indexTwo] = array[indexOne] ^ array[indexTwo];
        }
    }

    public static void swap(char[] array, int indexOne, int indexTwo) {
        if (indexOne != indexTwo) {
            char t = array[indexOne];
            array[indexOne] = array[indexTwo];
            array[indexTwo] = t;
        }
    }

    public static <T> void swap(List<T> list, int indexOne, int indexTwo) {
        if (indexOne != indexTwo) {
            T temp = list.get(indexOne);
            list.set(indexOne, list.get(indexTwo));
            list.set(indexTwo, temp);
        }
    }

    /**
     * 判断是否为纯数字的字符串
     *
     * @param str 字符串
     * @return 状态
     */
    public static boolean isNumber(String str) {
        Pattern pattern = Pattern.compile(Constants.NUM_STR1);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }

    public static <T> ListNode<T> createListNode(T[] array) {
        ListNode<T> root = new ListNode<>(array[0]);
        ListNode<T> node = root;
        int len = array.length;
        for (int i=1;i<len;i++) {
            node.setNext(new ListNode<>(array[i]));
            node = node.getNext();
        }
        return root;
    }
}
